package org.duanyu.controller;

import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 文字生成语音
 */
@RestController
public class TTSController {

    @Autowired
    private SpeechSynthesisModel speechSynthesisModel;

    /**
     * 文字生成语音
     * @param message
     */
    @GetMapping("/tts")
    public void tts(String message, HttpServletResponse response) throws IOException {
        SpeechSynthesisResponse speechSynthesisResponse = speechSynthesisModel.call(new SpeechSynthesisPrompt(message));
        ServletOutputStream outputStream = response.getOutputStream();
        ByteBuffer byteBuffer = speechSynthesisResponse.getResult().getOutput().getAudio();
        //设置响应头，告诉浏览器返回的是一个音频文件
        response.setContentType("audio/mpeg");
        response.setHeader("Content-Disposition","attachment; filename=tts.mp3");
        response.setContentLength(byteBuffer.array().length);

        outputStream.write(byteBuffer.array());
    }
}
